/*
 * @Author: cwd
 * @Date: 2022-03-01 16:01:35
 * @LastEditors: cwd
 * @LastEditTime: 2022-06-02 16:39:58
 * @FilePath: \koa2typecsript\src\main.ts
 * @Description: 
 * 
 * Copyright (c) 2022 by cwd, All Rights Reserved. 
 */
import Koa from 'koa';
import cors from '@koa/cors';
import bodyParser from 'koa-bodyparser';
// import { createConnection  }  from 'typeorm';
import { AppDataSource } from "./data-source"
import jwt from 'koa-jwt';
import 'reflect-metadata';
import { protectedRouter, unprotectedRouter } from './router/routers';

import { JWT_SECRET } from './JWTSecret/Secret';

AppDataSource.initialize().then(() => {
 
  // 初始化 Koa 应用实例 
  const app = new Koa();

  // 注册中间件
  app.use(cors());
  app.use(bodyParser());

  app.use(async (ctx, next) => {
    try {
      await next();
    } catch (err) {
      // 只返回 JSON 格式的响应
      ctx.status = err.status || 500;
      ctx.body = { err: err };
    }
  });

  // 响应请求

  //无需JWT Token可访问
  app.use(unprotectedRouter.routes()).use(unprotectedRouter.allowedMethods());

  // 注册 JWT 中间件
  app.use(jwt({ secret: JWT_SECRET }).unless({ path: [/^\/auth\/login/, /^\/auth\/register/] }));

  //需要JWT Token访问
  app.use(protectedRouter.routes()).use(protectedRouter.allowedMethods());

  // 运行服务器
  app.listen(3000);

}).catch((err: string) => console.log('TypeORM connection error:', err))
